let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');

// 科目每层id的长度

/**
 * 查询科目数据 by p 2018-06-11
 *
 * 按条件查询科目数据
 *
 */
function getSubjects(parentId, req, res) {
    req.app.db.query("select * from subject where id like ? and types = ? order by id", [(parentId + "%"), (parentId.length / global.SubjectIdLength)], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "data": results, "totalCount": results.length, "message": ""});
    });
}

router.get('/', filter.authorize, function (req, res, next) {
    getSubjects('', req, res);
});

router.get('/:id/books', filter.authorize, function (req, res, next) {
    getSubjects(req.params.id, req, res);
});

router.get('/:id/books/:bookId/chapters', filter.authorize, function (req, res, next) {
    getSubjects(req.params.bookId, req, res);
});

router.get('/:id/books/:bookId/chapters/:chapterId/sections', filter.authorize, function (req, res, next) {
    getSubjects(req.params.chapterId, req, res);
});

router.get('/zzzz', filter.authorize, function (req, res, next) {
    let params = req.query;
    var datas = [];
    var sql = "";
    let displayParent = params.displayParent === undefined ? "0" : params.displayParent;

    if (params.parentIds !== undefined && params.parentIds !== "") {
        let parentIds = params.parentIds.split(",");
        for (let i = 0; i < parentIds.length; i++) {
            if (displayParent === "1") {
                sql += (sql === "" ? "" : " or ") + "(id = ?)";
                datas.push(parentIds[i].substring(0, global.SubjectIdLength));
            }

            sql += (sql === "" ? "" : " or ") + "(id >= ? and id < ?)";
            datas.push(parentIds[i]);
            datas.push(formatSubjectId((Math.floor(parentIds[i]) + 1) + "", parentIds[i].length));
        }
    }

    sql = "select * from subject" + (sql === "" ? "" : " where " + sql + "order by id");
    req.app.db.query(sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }
        res.json({"success": true, "data": results, "totalCount": results.length, "message": ""});
    });
});

/**
 * 查看科目、册、章、节数据 by p 2018-06-11
 *
 * 按id查看指定的科目、册、章、节信息
 */
function getSubject(id, req, res) {
    req.app.db.query("select * from subject where id = ?", [id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
}

router.get('/:id', filter.authorize, function (req, res, next) {
    getSubject(req.params.id, req, res);
});

router.get('/:id/books/:bookId', filter.authorize, function (req, res, next) {
    getSubject(req.params.bookId, req, res);
});

router.get('/:id/books/:bookId/chapters/:chapterId', filter.authorize, function (req, res, next) {
    getSubject(req.params.chapterId, req, res);
});

router.get('/:id/books/:bookId/chapters/:chapterId/sections/:sectionId', filter.authorize, function (req, res, next) {
    getSubject(req.params.sectionId, req, res);
});

/**
 * 保存科目、册、章、节数据 by p 2018-06-11
 *
 * 支持新增、修改
 * id 大于 0时，修改
 * 其他情况 新增
 */
function saveSubject(parentId, params, req, res) {
    if (params.title === undefined || params.title === "") {
        res.json({"success": false, "message": "科目名不能为空！"});
        return;
    }

    if (params.types === undefined || params.types === "") {
        res.json({"success": false, "message": "必须指定科目类型！"});
    }

    if (params.id !== undefined && params.id !== "" && params.id > 0) {
        req.app.db.query("update subject set title = ?, types = ? where id = ?", [params.title, params.types, params.id], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (global.trees.length > 0) {
                global.trees.splice(0);
            }

            res.json({"success": true, "message": global.putMsg});
        });
    }
    else {
        let len = parentId.length + global.SubjectIdLength;
        req.app.db.query("select max(id) as id from subject where id like ? and length(id) = ?", [parentId + "%", len], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            var id = parentId + formatSubjectId("1", global.SubjectIdLength);
            if (results.length > 0 && results[0].id != null) {
                id = formatSubjectId((Math.floor(results[0].id) + 1) + "", parentId.length + global.SubjectIdLength);
            }

            req.app.db.query("insert into subject(title, types, id) values(?, ?, ?)", [params.title, params.types, id], function (err, results) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                if (global.trees.length > 0) {
                    global.trees.splice(0);
                }

                res.json({"success": true, "message": global.postMsg});
            });
        });
    }
}

router.put('/:id', filter.authorize, function (req, res, next) {
    saveSubject('', req.body, req, res);
});

router.put('/:id/books/:bookId', filter.authorize, function (req, res, next) {
    saveSubject(req.params.id, req.body, req, res);
});

router.put('/:id/books/:bookId/chapters/:chapterId', filter.authorize, function (req, res, next) {
    saveSubject(req.params.bookId, req.body, req, res);
});

router.put('/:id/books/:bookId/chapters/:chapterId/sections/:sectionId', filter.authorize, function (req, res, next) {
    saveSubject(req.params.chapterId, req.body, req, res);
});

router.post('/', filter.authorize, function (req, res, next) {
    saveSubject('', req.body, req, res);
});

router.post('/:id/books', filter.authorize, function (req, res, next) {
    saveSubject(req.params.id, req.body, req, res);
});

router.post('/:id/books/:bookId/chapters', filter.authorize, function (req, res, next) {
    saveSubject(req.params.bookId, req.body, req, res);
});

router.post('/:id/books/:bookId/chapters/:chapterId/sections', filter.authorize, function (req, res, next) {
    saveSubject(req.params.chapterId, req.body, req, res);
});

/**
 * 删除科目、册、章、节信息 by v 2018-06-11
 *
 * 按id删除指定的科目、册、章、节信息
 */

function deleteSubject(id, req, res) {
    req.app.db.query('delete from subject where id = ?', [id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (global.trees.length > 0) {
            global.trees.splice(0);
        }

        res.json({"success": true, "message": global.deleteMsg});
    });
}

router.delete('/:id', filter.authorize, function (req, res, next) {
    deleteSubject(req.params.id, req, res);
});

router.delete('/:id/books/:bookId', filter.authorize, function (req, res, next) {
    deleteSubject(req.params.bookId, req, res);
});

router.delete('/:id/books/:bookId/chapters/:chapterId', filter.authorize, function (req, res, next) {
    deleteSubject(req.params.chapterId, req, res);
});

router.delete('/:id/books/:bookId/chapters/:chapterId/sections/:sectionId', filter.authorize, function (req, res, next) {
    deleteSubject(req.params.sectionId, req, res);
});

function formatSubjectId(id, len) {
    var r = id;
    var index = Math.floor(id);
    for (var i = 0; i < len - id.length; i++) {
        r = "0" + r;
    }

    return r;
}

module.exports = router;